/**
 * 核心工具js v2.0.0
 * @author: Jie.
 * @date: 2020-12-15
 */
module.exports = {
  /**
   * 判断是否为Ios
   * */
  isIos(){
	  return uni.getSystemInfoSync().platform == "ios" 
  },
  /**
   * 判断是否为Android
   * */
  isAndroid(){
	  return uni.getSystemInfoSync().platform == "android"
  },
  /**
   * 判断是否为是手机app
   * */
  isApp(){
	  let result = false
	  //#ifdef APP-PLUS
		result = true
	  //#endif
	  return result
  },
  isH5(){
	  let result = false
	  //#ifdef H5
	  		result = true
	  //#endif
	  return result
  },
  isMp(){
	  let result = false
	  // #ifdef MP-WEIXIN
	  	  result = true
	  //#endif
	  return result
  },
  isUnsignNumber(val){
      if(val===0) return true;
      if(!val) return false;
      var reg = new RegExp("^[0-9,.]*$");
      return reg.test(val);
  },
  isNumber(val){
      if(val===0) return true;
      if(!val) return false;
      var reg = new RegExp("(^[0-9,.]*$)|(^-[0-9,.]*$)");
      return reg.test(val);
  },
  /**
   * 时间/日期格式化工具
   * @param {Long||String} date 转换的时间戳或者字符串
   * @param {String} fmt 转换格式 如:yyyy-MM-dd hh:mm
   * @return {String} 返回格式化后的时间
   * @author Jie.
   * */
  formatDate(date, fmt){
	if(!date) return ''
	if(typeof date == "number")
		date = new Date(date)
    if (/(y+)/.test(fmt)) {
      fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length))
    }
    let o = {
      'M+': date.getMonth() + 1,
      'd+': date.getDate(),
      'h+': date.getHours(),
      'm+': date.getMinutes(),
      's+': date.getSeconds()
    };
    for (let k in o) {
      if (new RegExp(`(${k})`).test(fmt)) {
          let str = o[k] + ''
          fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? str : padLeftZero(str))
      }
    }
    return fmt
  },
  /**
   * 文本转Date
   * @param {Object} str
   * @param {Object} format
   * @author Jie.
   */
  stringToDate(str, format) {
  	if (str instanceof Date) return str;
  	var pattern = format.replace(/(yyyy)/g, "([0-9]{4})").replace(/(yy)|(MM)|(dd)|(hh)|(mm)|(ss)/g, "([0-9]{2})").replace(
  			/[Mdhms]/g, "([0-9]{1,2})")
  		.replace(/(fff)/g, "([0-9]{1,3})");
  
  	var getIndex = function(expr1, expr2) {
  		var index = format.indexOf(expr1);
  		if (index == -1)
  			index = format.indexOf(expr2);
  		return index;
  	};
  	var today = new Date();
  	var returnDate;
  	if (new RegExp(pattern).test(str)) {
  		var yPos = getIndex("yyyy", "yy");
  		var mPos = getIndex("MM", "M");
  		var dPos = getIndex("dd", "d");
  		var hPos = getIndex("hh", "h");
  		var miPos = getIndex("mm", "m");
  		var sPos = getIndex("ss", "s");
  		var fPos = getIndex("fff");
  		var data = {
  			y: 0,
  			m: 0,
  			d: 0,
  			h: 0,
  			mi: 0,
  			s: 0,
  			f: 0
  		};
  		var pos = new Array(yPos + ",y", mPos + ",m", dPos + ",d", hPos + ",h", miPos + ",mi", sPos + ",s", fPos + ",f").sort(
  			function(a, b) {
  				a = parseInt(a.split(",")[0], 10);
  				b = parseInt(b.split(",")[0], 10);
  				return a == b ? 0 : (a > b ? 1 : -1);
  			});
  		var tmpIndex = 0;
  		var newPos = [];
  		for (var i = 0; i < pos.length; i++) {
  			if (parseInt(pos[i].split(",")[0], 10) != -1) {
  				newPos[tmpIndex] = pos[i];
  				tmpIndex++;
  			}
  		}
  		var m = str.match(pattern);
  		for (i = 1; i < m.length; i++) {
  			if (i === 0)
  				return;
  			var flag = newPos[i - 1].split(',')[1];
  			data[flag] = m[i];
  		}
  
  		data.y = data.y || today.getFullYear();
  		data.d = data.d || today.getDate();
  		if (data.f !== 0)
  			data.f = _full(data.f, "0", 3, false);
  
  		if (data.y.toString().length == 2)
  			data.y = parseInt("20" + data.y, 10);
  		data.m -= 1;
  		returnDate = new Date(data.y, data.m, data.d, data.h, data.mi, data.s, data.f);
  	}
  	return returnDate;
  },
  /**
   * 解析过滤条件
   * @param {Object} filterObject
   */
  getFilter(filterObject) {
  	var lt = ""
  	for (var filter in filterObject) {
  		var ft = filterObject[filter]
  		if (ft) lt += "(" + ft + ") and "
  	}
  	lt = lt.substring(0, lt.lastIndexOf(" and "))
  	return lt
  },
  /**
   * 获取时间数组
   * @param {Long||String} date 要获取时间数组的原时间
   * @param {String} type 最终转换类型 
   * @return {Array}
   * @author Jie.
   * */
  getDateArray(date,type){
	  if(typeof date == "number")
	  	date = new Date(date)
	  let aToday = date
	  let tYear=aToday.getFullYear().toString()
	  let tMonth=formatNum(aToday.getMonth()+1).toString()
	  let tDay=formatNum(aToday.getDate()).toString()
	  let tHours=formatNum(aToday.getHours()).toString()
	  let tMinutes=formatNum(aToday.getMinutes()).toString()
	  let tSeconds=formatNum(aToday.getSeconds()).toString()
	  if(type=="datetime")
		return [tYear,tMonth,tDay,tHours,tMinutes,tSeconds]
	  else if(type="date")
		return [tYear,tMonth,tDay]
  },
  /**
   * 字节大小转文本
   * @param {Long} limit 需要转换的字节大小
   * @return {String} 返回转换后的字符串 如:2kb
   * @author Jie.
   * */
  byteConvert(limit){
      var size = ""
      if(limit < 0.1 * 1024){                            //小于0.1KB，则转化成B
          size = limit.toFixed(2) + "b"
      }else if(limit < 0.1 * 1024 * 1024){            //小于0.1MB，则转化成KB
          size = (limit/1024).toFixed(2) + "kb"
      }else if(limit < 0.1 * 1024 * 1024 * 1024){        //小于0.1GB，则转化成MB
          size = (limit/(1024 * 1024)).toFixed(2) + "mb"
      }else{                                            //其他转化成GB
          size = (limit/(1024 * 1024 * 1024)).toFixed(2) + "gb"
      }
  
      var sizeStr = size + ""                        //转成字符串
      var index = sizeStr.indexOf(".")                    //获取小数点处的索引
      var dou = sizeStr.substr(index + 1 ,2)            //获取小数点后两位的值
      if(dou == "00"){                                //判断后两位是否为00，如果是则删除00                
          return sizeStr.substring(0, index) + sizeStr.substr(index + 3, 2)
      }
      return size
  },
  /**
   * 将html代码转换为文本
   * @param {String} html 需要转换的html文本
   * @return {String} 返回转换后的字符串
   * @author Jie.
   * */
  getHtmlText(html) {
      html += "";
      if (html && html != "null" && html != null) {
        var content = html
          .replace(/<\/?.+?>/g, "")
          .replace(/[ ]|[&nbsp;]/g, "")
        return content
      } else {
        return "无内容"
      }
  },
  /**
   * 电话号码检测
   * @param {String} phone 需要检查的手机号码
   * @return {Boolean} 返回是否正确
   * @author Jie.
   * */
  checkPhone(phone){
      if(!(/^1[34578]\d{9}$/.test(phone))){
          return false
      }
      return true
  },
  /**
   * 邮箱检测
   * @param {String} mail 需要检查的邮箱地址
   * @return {Boolean} 返回是否正确
   * @author Jie.
   * */
  checkMail(mail){
	//校验邮箱
    var strRegex = /^(\w-*\.*)+@(\w-?)+(\.\w{2,})+$/
    if(!strRegex.test(mail)){
        return false
    }
    return true
  },
  /**
   * 检查中国18位身份证号码是否正确
   * @param {String} cid 身份证号
   * @return {Boolean} 返回是否正确
   * @author Jie.
   * */
  checkCnId(cid){
      var strRegex=/^[1-9][0-9]{5}(19|20)[0-9]{2}((01|03|05|07|08|10|12)(0[1-9]|[1-2][0-9]|31)|(04|06|09|11)(0[1-9]|[1-2][0-9]|30)|02(0[1-9]|[1-2][0-9]))[0-9]{3}([0-9]|x|X)$/
      if(!strRegex.test(cid)){
          return false
      }
      return true
   },
   /*文字格式化*/
   strFormat(src) {
   	if (arguments.length == 0) return null;
   	var args = Array.prototype.slice.call(arguments, 1);
   	return src.replace(/\{(\d+)\}/g, function(m, i) {
   		return args[i]
   	})
   },
   /**
    * 身份证号加密
    * @param {String} cardNumber 身份证号
    * @author wujw
    * */
   cardEncrypt(cardNumber){
   	return cardNumber.replace(/^(.{6})(?:\d+)(.{4})$/, "$1****$2");
   },
   /**
    * 数字转换，保留最后两位
    * @param {String} num 数字
    * @author lwd
    * */
   formatToFixed(num=0) {
   	var num = num*1
   	return num.toFixed(2)
   },
   //单位中文转字符
   unitToChars(str){
   	let dict = {
   		'平方米':'m²',
   		'立方米':'m³',
   		'千米':'km',
   		'米':'m',
   		'厘米':'cm',
   		'升':'L',
   		'吨':'t',
   		'千克':'kg',
   		'克':'g',
   	}
   	return dict[str]?dict[str]:str;
   },
   /**
    * 链接参数封装
    * @param {String} url 链接
    * @param {Object} params 参数map
    * @author wujw
    */
   getLink(url,params){
   	if(params){
   		let paramStr = "";
   		for(let name in params){
   			paramStr+=`&${name}=${params[name]}`
   		}
   		if(paramStr){
   			url +=`?${paramStr.substr(1)}`
   		}
   	}
   	return url;
   },
   /**
    * 时间差计算
    * @param {Object} start
    * @param {Object} end
    * @param {Object} interval
    */
   dateDiff(start, end, interval) {
   	start = (typeof start == 'string') ? this.stringToDate(start) : start;
   	end = (typeof end == 'string') ? this.stringToDate(end) : end;
   	interval = (typeof interval == 'undefined') ? 'd' : interval;
   	switch (interval) {
   		case 's':
   			return parseInt((end - start) / this._msForSecond, 10);
   		case 'n':
   			return parseInt((end - start) / this._msForMinute, 10);
   		case 'h':
   			return parseInt((end - start) / this._msForHour, 10);
   		case 'd':
   			return parseInt((end - start) / this._msForDay, 10);
   		case 'w':
   			return parseInt((end - start) / this._msForWeek, 10);
   		case 'm':
   			return (end.getMonth() + 1) + ((end.getFullYear() - start.getFullYear()) * 12) - (start.getMonth() + 1);
   		case 'y':
   			return end.getFullYear() - start.getFullYear();
   	}
   },
   /**
    * 时间计算
    * @param {Object} datetime
    * @param {Object} num
    * @param {Object} interval
    */
   dateIncrease(datetime, num, interval) {
   	datetime = (typeof datetime == 'string') ? this.stringToDate(datetime) : datetime;
   	interval = (typeof interval == 'undefined') ? 'd' : interval;
   	switch (interval) {
   		case 's':
   			return new Date(Date.parse(datetime) + (this._msForSecond * num));
   		case 'n':
   			return new Date(Date.parse(datetime) + (this._msForMinute * num));
   		case 'h':
   			return new Date(Date.parse(datetime) + (this._msForHour * num));
   		case 'd':
   			return new Date(Date.parse(datetime) + (this._msForDay * num));
   		case 'w':
   			return new Date(Date.parse(datetime) + (this._msForWeek * num));
   		case 'm':
   			return new Date(datetime.getFullYear(), (datetime.getMonth()) + num, datetime.getDate(), datetime.getHours(),
   				datetime.getMinutes(),
   				datetime.getSeconds());
   		case 'q':
   			return new Date(datetime.getFullYear(), (datetime.getMonth()) + num * 3, datetime.getDate(), datetime.getHours(),
   				datetime.getMinutes(),
   				datetime.getSeconds());
   		case 'y':
   			return new Date((datetime.getFullYear() + num), datetime.getMonth(), datetime.getDate(), datetime.getHours(),
   				datetime.getMinutes(),
   				datetime.getSeconds());
   	}
   },
   _msForSecond: 1000,
   _msForMinute: 60000,
   _msForHour: 3600000,
   _msForDay: 86400000, // 24*60*60*1000
   _msForWeek: 86400000 * 7,
   /**
    * 金额加上逗号
    * @author Jie.
    */
   priceFormat(s, n) {  
       n = n > 0 && n <= 20 ? n : 2;  
       s = parseFloat((s + "").replace(/[^\d\.-]/g, "")).toFixed(n) + "";  
       var l = s.split(".")[0].split("").reverse(), r = s.split(".")[1];  
       t = "";  
       for (i = 0; i < l.length; i++) {  
           t += l[i] + ((i + 1) % 3 == 0 && (i + 1) != l.length ? "," : "");  
       }  
       return t.split("").reverse().join("") + "." + r;  
   }
}
var formatNum = function(num) {
	return num < 10 ? '0' + num : num + ''
}
var padLeftZero = function(str) {
	return ('00' + str).substr(str.length)
}
var _full = function(str, ch, count, isLeft) {
	while (str.length < count)
		if (isLeft) str = ch + str
	else str = str + ch
	return str
}